package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.IntegralRecord;
import com.zuipin.entity.MemberAccount;
import com.zuipin.entity.OrderInfo;
import com.zuipin.entity.product.EvaluationImg;
import com.zuipin.entity.product.EvaluationInfo;
import com.zuipin.entity.product.OverallEvaluation;
import com.zuipin.enums.IntegralType;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.mapper.EvaluationInfoMapper;
import com.zuipin.service.IEvaluationImgService;
import com.zuipin.service.IEvaluationInfoService;
import com.zuipin.service.IIntegralRecordService;
import com.zuipin.service.IMemberAccountService;
import com.zuipin.service.IOrderService;
import com.zuipin.service.IOverallEvaluationService;
import com.zuipin.service.IProductExtInfoService;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;
import com.zuipin.vo.EvaluationInfoVo;
import com.zuipin.vo.EvaluationVo;
import com.zuipin.vo.saveEvaluationVo;

import net.sf.json.JSONObject;

/**
 * 评价信息业务类实现
 *
 * @ClassName EvaluationInfoServiceImpl
 * @author wangcongyi
 * @date 2017年4月25日 下午2:36:15
 */
@Service
public class EvaluationInfoServiceImpl implements IEvaluationInfoService {
	
	@Resource
	private EvaluationInfoMapper		evaluationInfoMapper;
	@Resource
	private IEvaluationImgService		evaluationImgService;
	@Resource
	private IProductExtInfoService		productExtInfoService;
	// private EvaluationImgMapper evaluationImgMapper;
	@Resource
	private IMemberAccountService		memberAccountService;
	@Resource
	private IOverallEvaluationService	overallEvaluationService;
	@Resource
	private IIntegralRecordService		integralRecordService;
	@Resource
	private IOrderService				orderService;
	
	@Override
	public int deleteByPrimaryKey(Long id) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public int insert(EvaluationInfo record) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public int insertSelective(EvaluationInfo record) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public EvaluationInfo selectEvaluationInfo(EvaluationInfo eval) {
		// TODO Auto-generated method stub
		return evaluationInfoMapper.selectEvaluationInfo(eval);
	}
	
	@Override
	public int updateByPrimaryKeySelective(EvaluationInfo record) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public int updateByPrimaryKeyWithBLOBs(EvaluationInfo record) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public int updateByPrimaryKey(EvaluationInfo record) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public EvaluationInfoVo seachEvaluation(Short isExistImg, EvaluationInfo eval, Pagination page) {
		// TODO Auto-generated method stub
		EvaluationInfoVo evaluationInfoVo = new EvaluationInfoVo();
		List<EvaluationVo> vos = evaluationInfoMapper.seachEvaluation(isExistImg, eval, page);
		evaluationInfoVo.setEvaluations(vos);
		// 判断评论信息列表是否为空
		if (vos != null && !vos.isEmpty()) {
			// 获取4星以上好评数
			Integer praiseNum = getPraiseNum(eval);
			Integer praiseRate = new Integer(0);
			Integer totalRecord = evaluationInfoMapper.getProEvalNum(eval.getSysId(), eval.getProExtId());
			if (EvaluationInfo.ZERO != praiseNum || EvaluationInfo.ZERO != totalRecord) {
				BigDecimal praiseRecord = new BigDecimal(praiseNum);
				BigDecimal totalRecords = new BigDecimal(totalRecord);
				praiseRate = praiseRecord.divide(totalRecords, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).intValue();
			}
			evaluationInfoVo.setPraiseRate(praiseRate);
			List<Long> ids = new ArrayList<Long>();
			List<Long> memberIds = new ArrayList<Long>();
			// 装载查询条件 ID集合 和 会员ID 集合
			for (int i = 0; i < vos.size(); i++) {
				ids.add(vos.get(i).getId());
				memberIds.add(vos.get(i).getMemberId());
			}
			List<MemberAccount> memberAccounts = memberAccountService.findByMemberIdsAndSysId(memberIds, eval.getSysId());
			List<EvaluationImg> evaluationImgs = evaluationImgService.getEvaluationImgs(ids);
			// 装载晒图数eval.proExtId
			Integer slideShow = evaluationImgService.findslideShow(eval.getProExtId());
			evaluationInfoVo.setSlideShow(slideShow);
			// 循环装载会员等级 和 图片信息
			for (int i = 0; i < vos.size(); i++) {
				Iterator<MemberAccount> miterator = memberAccounts.iterator();
				while (miterator.hasNext()) {
					MemberAccount memberAccount = miterator.next();
					if (vos.get(i).getMemberId().equals(memberAccount.getMemberId())) {
						vos.get(i).setLevel(memberAccount.getMemberLevelId().toString());
						continue;
					}
				}
				List<EvaluationImg> tempEvalImgs = new ArrayList<EvaluationImg>();
				Iterator<EvaluationImg> iterator = evaluationImgs.iterator();
				while (iterator.hasNext()) {
					EvaluationImg img = iterator.next();
					if (vos.get(i).getId().equals(img.getEvaluationId())) {
						tempEvalImgs.add(img);
						iterator.remove();
					}
				}
				vos.get(i).setEvaluationImgs(tempEvalImgs);
			}
		}
		return evaluationInfoVo;
	}
	
	@Override
	public Integer getPraiseNum(EvaluationInfo eval) {
		// TODO Auto-generated method stub
		return evaluationInfoMapper.getPraiseNum(eval);
	}
	
	@Override
	public List<EvaluationVo> findEvaluation(EvaluationInfo eval, Pagination page) {
		// TODO Auto-generated method stub
		List<EvaluationVo> vos = evaluationInfoMapper.findEvaluation(eval, page);
		if (null != vos && !vos.isEmpty()) {
			List<Long> ids = new ArrayList<Long>();
			// 装载查询条件ID集合
			for (int i = 0; i < vos.size(); i++) {
				ids.add(vos.get(i).getId());
			}
			List<EvaluationImg> evaluationImgs = evaluationImgService.getEvaluationImgs(ids);
			// 循环装载图片信息
			for (int i = 0; i < vos.size(); i++) {
				List<EvaluationImg> tempEvalImgs = new ArrayList<EvaluationImg>();
				Iterator<EvaluationImg> iterator = evaluationImgs.iterator();
				while (iterator.hasNext()) {
					EvaluationImg img = iterator.next();
					if (vos.get(i).getId().equals(img.getEvaluationId())) {
						tempEvalImgs.add(img);
						iterator.remove();
					}
				}
				vos.get(i).setEvaluationImgs(tempEvalImgs);
			}
		}
		return vos;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveEvaluation(saveEvaluationVo vo, Integer reviewNum) throws CustomException {
		// TODO Auto-generated method stub
		// 获取当前时间
		String currentTime = DateUtils.getCurrentDateTime();
		OverallEvaluation overall = vo.getOverallEvaluation();
		// 获取整体评价内容 对数据进行严谨性处理
		overall.setCreateTime(currentTime);
		overall.setState(OverallEvaluation.NOT_ACTIVE);
		overall.setDelFlag(false);
		overall.setCreateId(null);
		overall.setUpdateTime(null);
		overall.setUpdateId(null);
		overallEvaluationService.insertSelective(overall);
		// 获取评价信息列表 对数据进行严谨性处理
		List<EvaluationInfo> evaluationInfos = vo.getEvaluationInfos();
		for (EvaluationInfo evaluationInfo : evaluationInfos) {
			evaluationInfo.setSysId(overall.getSysId());
			evaluationInfo.setOrderId(overall.getOrderId());
			evaluationInfo.setCreateTime(currentTime);
			evaluationInfo.setState(EvaluationInfo.CHECK_PENDING);
			evaluationInfo.setDelFlag(false);
			evaluationInfo.setCreateId(null);
			evaluationInfo.setUpdateId(null);
			evaluationInfo.setUpdateTime(null);
			evaluationInfo.setIsReply(null);
			evaluationInfo.setReplyContent(null);
			evaluationInfo.setReplyPerson(null);
			evaluationInfo.setReplyTime(null);
			evaluationInfo.setTopTime(null);
			evaluationInfoMapper.insertSelective(evaluationInfo);
			// 更新商品好评数！！！
			productExtInfoService.updateAssessmentNum(overall.getSysId(), evaluationInfo.getProExtId());
			// 获取评价图片列表 对数据进行严谨性处理
			List<EvaluationImg> evaluationImgs = evaluationInfo.getEvaluationImgs();
			if (null != evaluationImgs && !evaluationImgs.isEmpty()) {
				for (EvaluationImg evaluationImg : evaluationImgs) {
					evaluationImg.setEvaluationId(evaluationInfo.getId());
					evaluationImg.setCreateTime(currentTime);
					evaluationImg.setDelFlag(false);
					evaluationImg.setCreateId(null);
					evaluationImg.setUpdateId(null);
					evaluationImg.setUpdateTime(null);
				}
				evaluationImgService.insertBatch(evaluationImgs);
			}
		}
		// 获取评价人ID和系统ID
		Long memberId = evaluationInfos.get(0).getMemberId();
		Long sysId = overall.getSysId();
		// 评价成功对评价人进行积分赠送
		OrderInfo oi = orderService.findOrderInfoById(overall.getOrderId());
		integralRecordService.addIntegralRecord(memberId, sysId, null, null, reviewNum * EvaluationInfo.GIFT_POINTS, IntegralType.EVALUATION_SNED, "评价", "订单号",
				oi == null ? "" : oi.getOrderNo(), IntegralRecord.IS_BUY_NO);
		// 将该订单评论状态修改为已评论
		orderService.modityIsComment(overall.getOrderId());
		return true;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean verify(EvaluationInfo eval) {
		// TODO Auto-generated method stub
		// 获取当前时间
		String currentTime = DateUtils.getCurrentDateTime();
		OverallEvaluation overall = new OverallEvaluation();
		overall.setOrderId(eval.getOrderId());
		// 判断通过或屏蔽
		if (EvaluationInfo.PASS.equals(eval.getState())) {
			if (EvaluationInfo.TOP.equals(eval.getIsTop())) {
				eval.setTopTime(currentTime);
			}
			evaluationInfoMapper.modifyState(eval);
			overall.setState(OverallEvaluation.ACTIVE);
			overallEvaluationService.modifyState(overall);
		} else {
			eval.setTopTime(null);
			eval.setIsTop(EvaluationInfo.NO_TOP);
			evaluationInfoMapper.modifyState(eval);
			int num = evaluationInfoMapper.selectPassNum(eval);
			if (num == 0) {
				overall.setState(OverallEvaluation.NOT_ACTIVE);
				overallEvaluationService.modifyState(overall);
			}
		}
		return true;
	}
	
	@Override
	public boolean cancelTop(JSONObject params) {
		// TODO Auto-generated method stub
		return evaluationInfoMapper.cancelTop(params);
	}
	
	@Override
	public int insertBatch(List<EvaluationInfo> evaluationInfos) {
		// TODO Auto-generated method stub
		return evaluationInfoMapper.insertBatch(evaluationInfos);
	}
	
	@Override
	public boolean reply(EvaluationInfo eval) {
		// TODO Auto-generated method stub
		return evaluationInfoMapper.reply(eval);
	}
	
	@Override
	public Integer getNoEvaluatedNum(Long sysId) {
		// TODO Auto-generated method stub
		return evaluationInfoMapper.getNoEvaluatedNum(sysId);
	}
	
}
